//
//  NYDetailExerciseViewController.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/10.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NYDetailExerciseViewController.h"
#import "NYExamineTestActionCell.h"
#import "NYAddToGoodSubjectRequest.h"
#import "NYExamineTestSubmitSuccessViewController.h"
#import "NYExamineSubmitRequest.h"
#import "NYDetailExerciseSubmitAnswerRequest.h"
#import "NYSubjectTitleCell.h"
#import "NYSubjectAnswerCell.h"
#import "NYExamineTestTextViewCell.h"
#import "NYDetailExerciseSubmitCell.h"
#import "NYMyExamineDetailViewController.h"
#import "NYMyExamineDetailModel.h"
@interface NYDetailExerciseViewController ()

@end

@implementation NYDetailExerciseViewController

- (instancetype)initWithStyle:(UITableViewStyle)style
{
        return [super initWithStyle:UITableViewStyleGrouped];
}
- (void)viewDidLoad
{
        [super viewDidLoad];
        [self loadData];
        self.tableView.allowsMultipleSelection = YES;
        self.tableView.allowsSelection = YES;
        self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}
- (void)setDetailModel:(NYCourseModel *)detailModel
{
        _detailModel = detailModel;
        [self loadData];
}
- (void)loadData
{
        if (self.isViewLoaded)
        {
                if (self.detailModel.exercises.count <= 0) {
                        [self hideEmptyView];
                        [self showEmptyViewWithText:@"暂无练习题" detailText:@"" buttonTitle:nil buttonAction:nil];
                } else {
                        [self configNimbus];
                        [self configNimbusDataForMutableSections];
                }
        }
}
- (UITableViewCell *)tableViewModel:(NITableViewModel *)tableViewModel cellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
        UITableViewCell *cell = [super tableViewModel:tableViewModel cellForTableView:tableView atIndexPath:indexPath withObject:object];
        if ([cell isKindOfClass:[NYExamineTestActionCell class]]) {
                [self configActionCell:(NYExamineTestActionCell *)cell];
        } else if ([cell isKindOfClass:[NYDetailExerciseSubmitCell class]]) {
                [self configSubmitCell:(NYDetailExerciseSubmitCell *)cell];
        }
        return cell;
}
- (void)configSubmitCell:(NYDetailExerciseSubmitCell *)submitCell
{
        @weakify(self);
        [submitCell.submitBtn jk_addActionHandler:^(NSInteger tag) {
                @strongify(self);
                [self configAnswerAndSubmit];
        }];
}
- (void)configActionCell:(NYExamineTestActionCell *)actionCell
{
        @weakify(self);
        @weakify(actionCell);
        [actionCell setActionBlock:^(NYExamineTestActionType actionType,  NYSubjectModel *questionModel) {
                @strongify(self);
                @strongify(actionCell);
                switch (actionType) {
                        case NYExamineTestActionTypeAnalysis:
                        {
                                [self routeUrl:kNYSubjectAnalysisURI param:@{
                                                                             kRequestKeyType : @(NYSubjectAnalysisTypeExercise),
                                                                             kRequestKeyTypeID : NOT_NULL_STRING_DEFAULT_EMPTY(questionModel.id)
                                                                             }];
                        }
                                break;
                        case NYExamineTestActionTypeAddToGood:
                        {
                                [NYTipClass showLoadingInView:self.view];
                                [[NYAddToGoodSubjectRequest requestWithParams:@{
                                                                                kRequestKeyExercisesId : NOT_NULL_STRING_DEFAULT_EMPTY(questionModel.id),
                                                                                kRequestKeyTypeID : @(questionModel.genre),
                                                                                }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NSString * _Nonnull data) {
                                        [NYTipClass showText:request.tipString inView:self.view];
                                        questionModel.is_good = @"2";
                                        [self.tableView reloadRowAtIndexPath:[self.tableView indexPathForCell:actionCell] withRowAnimation:(UITableViewRowAnimationNone)];
                                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                                        [NYTipClass showErrorWithText:error.localizedDescription inView:self.view];
                                }];
                        }
                                break;
                                
                        default:
                                break;
                }
                
        }];
}

- (void)jumpToSuccessController:(NYExamineSubmitResModel *)data
{
        NYMyExamineDetailViewController *vc = [[NYMyExamineDetailViewController alloc] init];
        NYMyExamineDetailModel *detailModel = [[NYMyExamineDetailModel alloc] init];
        detailModel.page_info = data.page_info;
        detailModel.score_statistics = data.score_statistics;
        detailModel.results = [data.results sortedArrayUsingComparator:^NSComparisonResult(NYMyExamineResultModel *  _Nonnull obj1, NYMyExamineResultModel *  _Nonnull obj2) {
                return obj1.num.integerValue > obj2.num.integerValue;
        }];
        vc.analysisType = NYSubjectAnalysisTypeExercise;
        vc.detailModel = detailModel;
        [vc willMoveToParentViewController:self];
        [vc beginAppearanceTransition:YES animated:YES];
        [self addChildViewController:vc];
        [self.view addSubview:vc.view];
        [vc didMoveToParentViewController:self];
        [vc beginAppearanceTransition:NO animated:YES];
        [vc.view mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.view);
        }];
}
- (void)configAnswerAndSubmit
{
        [NYTipClass showLoadingInView:self.view];
        NSMutableDictionary <NSString *, NSString *>*answerDict = @{}.mutableCopy;
        NSMutableDictionary <NSString *,NSIndexPath *>*unAnswerDict = @{}.mutableCopy;
        [self.detailModel.exercises enumerateObjectsUsingBlock:^( NYSubjectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.user_answer != nil)
                {
                        [answerDict setObject:obj.user_answer forKey:[NSString stringWithFormat:@"answer%d",(int)idx+1]];
                }
        }];
        [self configUnAnswerQuestionAnswerDict:answerDict unAnswerDict:unAnswerDict];
        
}
- (void)configUnAnswerQuestionAnswerDict:(NSMutableDictionary <NSString *, NSString *>*)answerDict unAnswerDict:(NSMutableDictionary <NSString *,NSIndexPath *>*)unAnswerDict
{
        if (answerDict.count == self.detailModel.exercises.count)
        {
                /// 提交答案
                [[NYDetailExerciseSubmitAnswerRequest requestWithParams:@{
                                                                          @"video_id" : @(self.detailModel.currentPlayModel.id),
                                                                          @"answer" : answerDict.jsonStringEncoded
                                                                          }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYExamineSubmitResModel * _Nonnull data) {
                        [NYTipClass hideLoadingInView:self.view];
                        [self jumpToSuccessController:data];
                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                        [NYTipClass showText:error.localizedDescription inView:self.view];
                }];
        }
        else
        {
                [NYTipClass showText:@"您有答案未填写，请完成后提交" inView:self.view];
        }
}

- (void)configChoiceAnswer:( NYSubjectModel *)subjectObj atIndexPath:(NSIndexPath *)indexPath
{
        if (subjectObj.question_type != NYQuestionTypeFillBlanks)
        {
                subjectObj.user_answer = nil;
                NSMutableArray *resArr = @[].mutableCopy;
                [self.tableView.indexPathsForSelectedRows enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (obj.section == indexPath.section)
                        {
                                [resArr addObject:@(obj.row).stringValue];
                        }
                }];
                subjectObj.user_answer = resArr;
        }
        
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
        NICellObject *obj = [self.tableViewModel objectAtIndexPath:indexPath];
        [self configChoiceAnswer:obj.userInfo atIndexPath:indexPath];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        NICellObject *obj = [self.tableViewModel objectAtIndexPath:indexPath];
        [self configChoiceAnswer:obj.userInfo atIndexPath:indexPath];
}
- (void)configNimbus
{
        [super configNimbus];
        @weakify(self);
        [self.tableViewActions forwardingTo:self.controllerView];
        [self.tableViewActions attachToClass:[NICellObject class] tapBlock:^BOOL(NICellObject * object, NYDetailExerciseViewController * target, NSIndexPath *indexPath) {
                @strongify(self);
                NYSubjectModel *subjectObj = object.userInfo;
                
                /// return YES 会调用 deselectRowAtIndexPath 方法， return NO 则不会调用
                /// 标题
                if (indexPath.row == 0)
                {
                        return YES;
                }
                /// 填空题
                if (subjectObj.question_type == NYQuestionTypeFillBlanks)
                {
                        return YES;
                }
                
                /// 每组最后一个 actionCell
                /// 已做过，才会出现查看解析，或者加入好题本 的 actionCell
                if (subjectObj.is_test.integerValue == 2 && indexPath.row + 1 == [target.tableViewModel countInSection:indexPath.section]) {
                        return YES;
                }
                /// 单项选择题
                if (subjectObj.question_type == NYQuestionTypeSingleChoice)
                {
                        /// 判断当前是否有选项选择
                        [target.tableView.indexPathsForVisibleRows enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                                if (obj.section == indexPath.section && obj.row != indexPath.row)
                                {
                                        [target.tableView deselectRowAtIndexPath:obj animated:NO];
                                }
                        }];
                        return NO;
                }
                /// 多选题
                return NO;
        }];
}
- (void)configNimbusDataForMutableSections
{
        [self.detailModel.exercises enumerateObjectsUsingBlock:^( NYSubjectModel * _Nonnull subjectObj, NSUInteger subjectIdx, BOOL * _Nonnull subjectStop) {
                
                [self.tableViewModel addSectionWithTitle:nil];
                [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYSubjectTitleCell class] userInfo:subjectObj]];
                if (subjectObj.question_type != NYQuestionTypeFillBlanks && subjectObj.exercises_answer_arr.count > 0) {
                        [subjectObj.exercises_answer_arr enumerateObjectsUsingBlock:^(NSString * _Nonnull daanObj, NSUInteger daanIdx, BOOL * _Nonnull daanStop) {
                                [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYSubjectAnswerCell class] userInfo:subjectObj]];
                        }];
                }
                else
                {
                        [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYExamineTestTextViewCell class] userInfo:subjectObj]];
                }
                /// 已做过，才会出现查看解析，或者加入好题本
                if (subjectObj.is_test.integerValue == 2)
                {
                        [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYExamineTestActionCell class] userInfo:subjectObj]];
                }
        }];
        [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYDetailExerciseSubmitCell class] userInfo:self.detailModel]];
        [self.tableView reloadData];
}

@end
